/**
 * @param {number[][]} grid
 * @return {number}
 */
var closedIsland = function (grid) {
  let canChange = new Array(grid.length);
  let count = 0;
  for(let i = 0; i < grid.length; i++) {
    canChange[i] = new Array(grid[0].length).fill(true);
  }
  // 判断位置是否有效
  function isValidPosition(i, j) {
    return (i < grid.length && i >= 0) && (j < grid[0].length && j >= 0);
  }
  function dfs(i, j) {
    grid[i][j] = 1;

    // 上
    if(isValidPosition(i - 1, j) && !grid[i - 1][j]) {
      dfs(i - 1, j);
    }
    // 下
    if(isValidPosition(i + 1, j) && !grid[i + 1][j]) {
      dfs(i + 1, j);
    }
    // 左
    if(isValidPosition(i, j - 1) && !grid[i][j - 1]) {
      dfs(i, j - 1);
    }

    // 右
    if(isValidPosition(i, j + 1) && !grid[i][j + 1]) {
      dfs(i, j + 1);
    }

  }
  // 上下
  let i = 0;
  for(let j = 0; j < grid[0].length; j++) {
    if(!grid[i][j])
      dfs(i, j);
  }
  i = grid.length - 1;
  for(let j = 0; j < grid[0].length; j++) {
    if(!grid[i][j])
      dfs(i, j);
  }
  // 左右
  i = 0;
  for(let j = 1; j < grid.length; j++) {
    if(!grid[j][i])
      dfs(j, i);
  }
  i = grid[0].length - 1;
  for(let j = 1; j < grid.length; j++) {
    if(!grid[j][i])
      dfs(j, i);
  }
  for(let i = 0; i < grid.length; i++) {
    for(let j = 0; j < grid[0].length; j++) {
      if(!grid[i][j]) {
        count++;
        dfs(i, j);
      }
    }
  }

  return count;
};
let grid = [
  [1, 1, 1, 1, 1, 1, 1, 0],
  [1, 0, 0, 0, 0, 1, 1, 0],
  [1, 0, 1, 0, 1, 1, 1, 0],
  [1, 0, 0, 0, 0, 1, 0, 1],
  [1, 1, 1, 1, 1, 1, 1, 0]
];
console.log(closedIsland(grid));
grid = [
  [0, 0, 1, 0, 0],
  [0, 1, 0, 1, 0],
  [0, 1, 1, 1, 0]
];
console.log(closedIsland(grid));
grid = [
  [1, 1, 1, 1, 1, 1, 1],
  [1, 0, 0, 0, 0, 0, 1],
  [1, 0, 1, 1, 1, 0, 1],
  [1, 0, 1, 0, 1, 0, 1],
  [1, 0, 1, 1, 1, 0, 1],
  [1, 0, 0, 0, 0, 0, 1],
  [1, 1, 1, 1, 1, 1, 1]
];
console.log(closedIsland(grid));
